package com.zh.work.util.plateform;

import com.alibaba.fastjson.JSON;
import com.zh.common.entity.ImageEntity;
import com.zh.common.entity.JSONResult;
import com.zh.work.constant.MerchInfoConstants;
import com.zh.work.dao.platform.agent.AgentInfoMapper;
import com.zh.work.entity.SaleRate;
import com.zh.work.entity.agent.AgentInfoEntity;
import com.zh.work.entity.agent.QrCodeAgentFee;
import com.zh.work.entity.branch.BranchAppEntity;
import com.zh.work.entity.branch.BranchInfoEntity;
import com.zh.work.entity.merch.MerchInfoEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 业务工具类，用于构造添加时实体信息
 * @Author: Li.HuiNeng
 * @Create in: 2019-11-16 16:33
 * @Version: 1.0.1
 */

@Component
public class ServiceUtil {
    private static final Logger log = LoggerFactory.getLogger(ServiceUtil.class);

    private static AgentInfoMapper agentInfoMapper;

    @Autowired
    public ServiceUtil(AgentInfoMapper agentInfoMapperBean) {
        ServiceUtil.agentInfoMapper = agentInfoMapperBean;
    }


    /**
     * 构造代理商编号
     *
     * @param areaCode 地区编码
     * @return
     * @throws Exception
     */
    public static String getAgentMaxId(String areaCode) throws Exception {
        String maxId = agentInfoMapper.getAgentMaxId(areaCode);
        if ((maxId == null) || (maxId.trim().equals("")))
            maxId = "1";
        else {
            maxId = "000000" + (Integer.parseInt(maxId) + 1);
            maxId = maxId.trim();
        }
        maxId = "0000" + maxId;
        maxId = maxId.trim();
        maxId = maxId.substring(maxId.length() - 4);
        return maxId;
    }

    /**
     * 构造商户编号
     *
     * @param merchNo 商户编号
     * @return
     * @throws Exception
     */
    public static String getMerchMaxId(String merchNo) {
        String obj = null;
        try {
            obj = agentInfoMapper.getMerchMaxId(merchNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isNotEmpty(obj)) {
            obj = "0";
        }
        int max = Integer.parseInt(obj) + 1;
        String id = "0000" + max;
        return id.substring(id.length() - 4);
    }

    /**
     * 构造商户实体信息
     *
     * @param agentInfo 代理商信息
     * @param branchAppEntity 机构APP信息
     * @return
     */
    public static MerchInfoEntity creatMerchBean(AgentInfoEntity agentInfo, BranchAppEntity branchAppEntity, String mcc) {
        MerchInfoEntity merch = new MerchInfoEntity();
        String merchNo = creatMerchantNo(agentInfo.getBranchNo(), agentInfo.getProvinceCity(), mcc);
        merch.setMerchNo(merchNo);
        merch.setProvinceCity(agentInfo.getProvinceCity());
        merch.setMerchName(agentInfo.getAgentName());
        merch.setFullName(agentInfo.getFullName());
        //默认开通二维码和mpos
        merch.setMerchType(5);
        merch.setLegalName(agentInfo.getLegalName());
        merch.setIdentityCard(agentInfo.getIdentityCard());
        merch.setLinkMan(agentInfo.getLinkMan());
        merch.setEmail(agentInfo.getEmail());
        merch.setTelephone(agentInfo.getTelephone());
        merch.setMobile(agentInfo.getMobile());
        merch.setAddress(agentInfo.getAddress());
        merch.setMcc(MerchInfoConstants.suffix);
        merch.setMerchLevel(1); // 商户级别
        merch.setBizType(agentInfo.getBizType());
        merch.setBranchNo(agentInfo.getBranchNo());
        merch.setFirstAgentNo(agentInfo.getAgentNo());
        merch.setAuditAgentNo(agentInfo.getBranchNo());
        merch.setSuperAgent(agentInfo.getAgentNo());
        merch.setTransCtrl(3);
        //默认线上费率
        merch.setManuRate(MerchInfoConstants.manuRate);
        merch.setAccountType(agentInfo.getAccountType());
        merch.setAccountNo(agentInfo.getAccountNo());
        merch.setAccountName(agentInfo.getAccountName());
        merch.setBankNo(agentInfo.getBankNo());
        merch.setBankName(agentInfo.getBankName());
        merch.setAgentFeeId(0);
        //传统POS费率
        merch.setDebitRate(MerchInfoConstants.debitRate);
        merch.setDebitFixed(MerchInfoConstants.debitFixed);
        merch.setCreditRate(MerchInfoConstants.creditRate);
        merch.setT0Rate(MerchInfoConstants.t0Rate);
        // 交易密匙
        merch.setMerchKey(RandomWordUtil.randomWord(32));
        //mpos费率
        if (branchAppEntity.getOpenSale() == 1) {
            //低级借记卡费率
            SaleRate debit = agentInfoMapper.getMPosRate(new SaleRate(agentInfo.getBranchNo(), 1, 2, 4));
            //低级信用卡费率
            SaleRate credit = agentInfoMapper.getMPosRate(new SaleRate(agentInfo.getBranchNo(), 2, 2, 4));
            //低级t+0费率
            SaleRate t0 = agentInfoMapper.getMPosRate(new SaleRate(agentInfo.getBranchNo(), 0, 1, 4));
            if (debit != null && credit != null && t0 != null) {
                merch.setAppRate(debit.getRate());
                merch.setAppFixed(Float.valueOf(debit.getFixed()));
                merch.setAppCredit(credit.getRate());
                merch.setAppT0Rate(t0.getRate());
            } else {
                merch.setDebitRate(branchAppEntity.getMposDebitRate());
                merch.setDebitFixed(branchAppEntity.getMposDebitFixed());
                merch.setCreditRate(branchAppEntity.getMposCreditRate());
                merch.setT0Rate(branchAppEntity.getMposT0Add());
            }
        } else {
            merch.setDebitRate(branchAppEntity.getMposDebitRate());
            merch.setDebitFixed(branchAppEntity.getMposDebitFixed());
            merch.setCreditRate(branchAppEntity.getMposCreditRate());
            merch.setT0Rate(branchAppEntity.getMposT0Add());
        }
        //磁条卡封顶金额
        merch.setStripeCardFixed(MerchInfoConstants.stripeCardFixed);
        //芯片卡封顶金额
        merch.setChipCardFixed(MerchInfoConstants.chipCardFixed);
        // 分销级别(0-底价 1-BOSS 2-高级 3-中级 4-低级)
        merch.setSaleLevel(4);
        //已注册
        merch.setStatus(0);

        return merch;
    }

    public static String creatMerchantNo(String branchNo, String provinceCity, String mcc) {
        // 获取 录入公司的 业务编码
        String bizCode = MerchInfoConstants.bizCode;
        if (!StringUtils.isNotEmpty(branchNo) && !MerchInfoConstants.systemNo.equals(branchNo)) {
            bizCode = agentInfoMapper.getBranchBizCode(branchNo);
        }
        // 生成商户编号
        List<String> list = JSON.parseArray(provinceCity, String.class);
        String areaCode = list.get(list.size() - 1);
        String prefix = bizCode + areaCode.substring(0, 4) + mcc;
        try {
            return prefix + getMerchMaxId(prefix);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取商户编号出错");
        }
    }

    /**
     * 验证二维码费率信息
     *
     * @param feeList       入参代理商信息
     * @param agentFeesList 原数据库信息
     * @return
     */
    public static int qrCodeFeeValid(List<QrCodeAgentFee> feeList, List<QrCodeAgentFee> agentFeesList) {
        int count = 0;
        // 提交的费率与原费率长度相等，则作比较
        if (feeList.size() == agentFeesList.size()) {
            // 对比具体值是否相等
            for (int i = 0; i < agentFeesList.size(); i++) {
                if (feeList.get(i).getRate() < agentFeesList.get(i).getRate())
                    --count;
                else
                    ++count;
            }
        }
        return count;
    }

    /**
     * 辅助方法，设置图片信息
     *
     * @param agentInfoEntity
     * @throws RuntimeException
     */
    public static void setImageInfo(AgentInfoEntity agentInfoEntity, MerchInfoEntity merchInfoEntity) throws RuntimeException {
        // 图片变量信息
        try {
            ImageEntity imageEntity = new ImageEntity();
            if (Objects.nonNull(agentInfoEntity)) {
                imageEntity = JSON.parseObject(agentInfoEntity.getImgJsonString(), ImageEntity.class);
                agentInfoEntity.setCashierImg(imageEntity.getCashierImg());
                agentInfoEntity.setContractImg(imageEntity.getContractImg());
                agentInfoEntity.setCard1Img(imageEntity.getCard1Img());
                agentInfoEntity.setCard2Img(imageEntity.getCard2Img());
                agentInfoEntity.setBizLicenseImg(imageEntity.getBizLicenseImg());
                agentInfoEntity.setPlaceImg(imageEntity.getPlaceImg());
                agentInfoEntity.setCorporationStoreImg(imageEntity.getCorporationStoreImg());
                agentInfoEntity.setCompanyStoreImg(imageEntity.getCompanyStoreImg());
                agentInfoEntity.setIdentity1Img(imageEntity.getIdentity1Img());
                agentInfoEntity.setIdentity2Img(imageEntity.getIdentity2Img());
                agentInfoEntity.setIdentity3Img(imageEntity.getIdentity3Img());
                agentInfoEntity.setOtherFile(imageEntity.getOtherFile());
            } else if (Objects.nonNull(merchInfoEntity)){
                imageEntity = JSON.parseObject(merchInfoEntity.getImgJsonString(), ImageEntity.class);
                assert imageEntity != null;
                merchInfoEntity.setCashierImg(imageEntity.getCashierImg());
                merchInfoEntity.setContractImg(imageEntity.getContractImg());
                merchInfoEntity.setCard1Img(imageEntity.getCard1Img());
                merchInfoEntity.setCard2Img(imageEntity.getCard2Img());
                merchInfoEntity.setBizLicenseImg(imageEntity.getBizLicenseImg());
                merchInfoEntity.setPlaceImg(imageEntity.getPlaceImg());
                merchInfoEntity.setCorporationStoreImg(imageEntity.getCorporationStoreImg());
                merchInfoEntity.setCompanyStoreImg(imageEntity.getCompanyStoreImg());
                merchInfoEntity.setIdentity1Img(imageEntity.getIdentity1Img());
                merchInfoEntity.setIdentity2Img(imageEntity.getIdentity2Img());
                merchInfoEntity.setIdentity3Img(imageEntity.getIdentity3Img());
                merchInfoEntity.setOtherFile(imageEntity.getOtherFile());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("图片信息解析错误");
        }
    }

    /**
     * 验证出二维码之外的费率信息
     *
     * @param agentInfoEntity  入参代理商信息
     * @param agentInfoParent  原数据库代理商信息
     * @param branchInfoEntity 原数据库机构信息
     * @return
     */
    public static int branchFeeValid(AgentInfoEntity agentInfoEntity, AgentInfoEntity agentInfoParent, BranchInfoEntity branchInfoEntity) {
        if (branchInfoEntity != null) {
            log.info("快捷0费率对比" + branchInfoEntity.getQuickT0Cost().compareTo(agentInfoEntity.getQuickRateT0()));
            if (branchInfoEntity.getQuickT0Cost().compareTo(agentInfoEntity.getQuickRateT0()) < 0) return -3;
            log.info("快捷1费率对比" + branchInfoEntity.getQuickT1Cost().compareTo(agentInfoEntity.getQuickRateT1()));
            if (branchInfoEntity.getQuickT1Cost().compareTo(agentInfoEntity.getQuickRateT1()) < 0) return -4;
            // 网关费率
            log.info("网关0对比" + branchInfoEntity.getGatewayRateT0().compareTo(agentInfoEntity.getGatewayRateT0()));
            if (branchInfoEntity.getGatewayRateT0().compareTo(agentInfoEntity.getGatewayRateT0()) < 0) return -5;
            log.info("网关1对比" + branchInfoEntity.getGatewayRateT1().compareTo(agentInfoEntity.getGatewayRateT1()));
            if (branchInfoEntity.getGatewayRateT1().compareTo(agentInfoEntity.getGatewayRateT1()) < 0) return -6;
            // T1封顶值
            // 传统pos 借记卡费率
            log.info("借记卡POS费率对比" + agentInfoEntity.getPosDebitRate().compareTo(new BigDecimal(0.0055)));
            if (agentInfoEntity.getPosDebitRate().compareTo(new BigDecimal(0.0055)) < 0) return -7;
            log.info("借记卡POS封顶对比" + agentInfoEntity.getPosDebitFixed().compareTo(new BigDecimal(25)));
            if (agentInfoEntity.getPosDebitFixed().compareTo(new BigDecimal(25)) < 0) return -8;
            // 传统pos 信用卡费率
            log.info("信用卡POS费率对比" + agentInfoEntity.getPosCreditRate().compareTo(new BigDecimal(0.0065)));
            if (agentInfoEntity.getPosCreditRate().compareTo(new BigDecimal(0.0065)) < 0) return -9;
            // 手机App借记卡费率
            log.info("借记卡APP费率对比" + agentInfoEntity.getAppDebitRate().compareTo(new BigDecimal(0.0065)));
            if (agentInfoEntity.getAppDebitRate().compareTo(new BigDecimal(0.0065)) < 0) return -10;
            // 手机App信用卡费率
            log.info("信用卡APP费率对比" + agentInfoEntity.getAppCreditRate().compareTo(new BigDecimal(0.0065)));
            if (agentInfoEntity.getAppCreditRate().compareTo(new BigDecimal(0.0065)) < 0) return -11;
        }
        if (agentInfoParent != null) {
            log.info("快捷T+0成本费率对比,上级费率: " + agentInfoParent.getQuickRateT0() + "，下级费率:" + agentInfoEntity.getQuickRateT0()
                    + "比对结果:" + agentInfoParent.getQuickRateT0().compareTo(agentInfoEntity.getQuickRateT0()));
            if (agentInfoParent.getQuickRateT0().compareTo(agentInfoEntity.getQuickRateT0()) > 0) return -3;
            log.info("快捷T+1成本费率对比,上级费率：" + agentInfoParent.getQuickRateT1() + "下级费率：" + agentInfoEntity.getQuickRateT1()
                    + "比对结果：" + agentInfoParent.getQuickRateT1().compareTo(agentInfoEntity.getQuickRateT1()));
            if (agentInfoParent.getQuickRateT1().compareTo(agentInfoEntity.getQuickRateT1()) > 0) return -4;
            // 网关费率
            log.info("网关0费率对比,上级费率：" + agentInfoParent.getGatewayRateT0() + "下级费率：" + agentInfoEntity.getGatewayRateT0()
                    + "比对结果：" + agentInfoParent.getGatewayRateT0().compareTo(agentInfoEntity.getGatewayRateT0()));
            if (agentInfoParent.getGatewayRateT0().compareTo(agentInfoEntity.getGatewayRateT0()) > 0) return -5;
            log.info("网关1费率对比,上级费率：" + agentInfoParent.getGatewayRateT1() + "下级费率： " + agentInfoEntity.getGatewayRateT1()
                    + "比对结果：" + agentInfoParent.getGatewayRateT1().compareTo(agentInfoEntity.getGatewayRateT1()));
            if (agentInfoParent.getGatewayRateT1().compareTo(agentInfoEntity.getGatewayRateT1()) > 0) return -6;
            // 传统pos 借记卡费率
            log.info("借记卡POS费率对比,上级费率：" + agentInfoParent.getPosDebitRate() + "下级费率：" + agentInfoEntity.getPosDebitRate()
                    + "比对结果：" + agentInfoParent.getPosDebitRate().compareTo(agentInfoEntity.getPosDebitRate()));
            if (agentInfoParent.getPosDebitRate().compareTo(agentInfoEntity.getPosDebitRate()) > 0) return -7;
            log.info("借记卡POS封顶对比,上级费率：" + agentInfoParent.getPosDebitFixed() + "下级费率：" + agentInfoEntity.getPosDebitFixed()
                    + "比对结果：" + agentInfoParent.getPosDebitFixed().compareTo(agentInfoEntity.getPosDebitFixed()));
            if (agentInfoParent.getPosDebitFixed().compareTo(agentInfoEntity.getPosDebitFixed()) > 0) return -8;
            // 传统pos 信用卡费率
            log.info("传统pos费率对比,上级费率：" + agentInfoParent.getPosCreditRate() + "下级费率：" + agentInfoEntity.getPosCreditRate()
                    + "比对结果：" + agentInfoParent.getPosCreditRate().compareTo(agentInfoEntity.getPosCreditRate()));
            if (agentInfoParent.getPosCreditRate().compareTo(agentInfoEntity.getPosCreditRate()) > 0) return -9;
            log.info("快捷0费率对比,上级费率：" + agentInfoParent.getQuickRateT0() + "下级费率：" + agentInfoEntity.getQuickRateT0()
                    + "比对结果：" + agentInfoParent.getQuickRateT0().compareTo(agentInfoEntity.getQuickRateT0()));
            // 手机App借记卡费率
            log.info("手机App借记卡费率对比,上级费率：" + agentInfoParent.getAppDebitRate() + "下级费率： " + agentInfoEntity.getAppDebitRate()
                    + "比对结果：" + agentInfoParent.getAppDebitRate().compareTo(agentInfoEntity.getAppDebitRate()));
            if (agentInfoParent.getAppDebitRate().compareTo(agentInfoEntity.getAppDebitRate()) > 0) return -10;
            // 手机App信用卡费率
            log.info("手机App信用卡费率对比,上级费率： " + agentInfoParent.getAppCreditRate() + "下级费率： " + agentInfoEntity.getAppCreditRate()
                    + "比对结果：" + agentInfoParent.getAppCreditRate().compareTo(agentInfoEntity.getAppCreditRate()));
            if (agentInfoParent.getAppCreditRate().compareTo(agentInfoEntity.getAppCreditRate()) > 0) return -11;
        }
        return 1;
    }

    /**
     * @Description: 费率信息验证消息提示
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/12/6
     */
    public static void msg(int i, JSONResult jsonResult) {
        switch (i) {
            case -1:
                jsonResult.setMessage("添加失败,新增代理商错误!");
                break;
            case -2:
                jsonResult.setMessage("添加失败,请检查二维码成本费率是否大于默认费率");
                break;
            case -3:
                jsonResult.setMessage("添加失败,请重新设置【快捷T+0】费率,添加值不能小于默认值");
                break;
            case -4:
                jsonResult.setMessage("添加失败,请重新设置【快捷T+1】费率,添加值不能小于默认值");
                break;
            case -5:
                jsonResult.setMessage("添加失败,请重新设置【网关T+0】费率,添加值不能小于默认值");
                break;
            case -6:
                jsonResult.setMessage("添加失败,请重新设置【网关T+1】费率,添加值不能小于默认值");
                break;
            case -7:
                jsonResult.setMessage("添加失败,请重新设置【传统POS借记卡】费率,添加值不能小于默认值");
                break;
            case -8:
                jsonResult.setMessage("添加失败,请重新设置【传统POS借记卡封顶】费率,添加值不能小于默认值");
                break;
            case -9:
                jsonResult.setMessage("添加失败,请重新设置【传统POS信用卡封顶】费率,添加值不能小于默认值");
                break;
            case -10:
                jsonResult.setMessage("添加失败,请重新设置【手机App借记卡】费率,添加值不能小于默认值");
                break;
            case -11:
                jsonResult.setMessage("添加失败,请重新设置【手机App信用卡】费率,添加值不能小于默认值");
                break;
            case -12:
                jsonResult.setMessage("添加失败,请重新设置【二维码】费率,添加值不能小于默认值");
                break;
            case -13:
                jsonResult.setMessage("添加失败,请重新设置【二维码】费率,二维码费率添加数量不相等");
                break;
            case -14:
                jsonResult.setMessage("添加失败,【二维码费率为空】");

        }
    }

    public static String getCardNo(String str,String branchNo){
        StringBuffer cardNo = new StringBuffer();
        cardNo.append(branchNo);
        if (StringUtils.isEmpty(str)) {
            str = "00000001";
        } else {
            int num = Integer.parseInt(str);
            str = "0000000" + (++num);
            str = str.substring(str.length() - 8);
        }
        cardNo.append(str);
        return  cardNo.toString();
    }
}
